package com.lrd.snapshotorder.service.orderconsumer;

import com.lrd.snapshotorder.entity.SnapshotOrder;
import com.lrd.snapshotorder.mapper.SnapshotOrderMapper;
import org.redisson.api.RBlockingDeque;

import java.util.concurrent.ThreadPoolExecutor;

public class OrderGeneratorConsumer2 {

    private ThreadPoolExecutor orderExecutorPool;
    private SnapshotOrderMapper snapshotOrderMapper;
    private RBlockingDeque rBlockingDeque;

    public OrderGeneratorConsumer2(ThreadPoolExecutor orderExecutorPool, SnapshotOrderMapper snapshotOrderMapper, RBlockingDeque rBlockingDeque) {
        this.orderExecutorPool = orderExecutorPool;
        this.snapshotOrderMapper = snapshotOrderMapper;
        this.rBlockingDeque = rBlockingDeque;
    }

    public void execute() {
        boolean again = true;
        while (again) {
            SnapshotOrder order = (SnapshotOrder) rBlockingDeque.poll();
            if (order != null) {
                orderExecutorPool.execute(() -> {
                    snapshotOrderMapper.insert(order);
                });
            } else {
                again = false;
                orderExecutorPool.shutdownNow();
            }
        }
    }
}
